#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

int num[] = {1,2,3,4,5,6,7,8,9,10};
sem_t sem1, sem2;

void *fun1(void *arg)
{
    int i;
    sem_wait(&sem1);    //申请信号量1
    for(i = 0; i < 10; i++)
    {
        printf("thread1--%d\n", num[i]);
    }
    sem_post(&sem2);    //释放信号量2
    pthread_exit(NULL);
}

void *fun2(void *arg)
{
    int i;
    sem_wait(&sem2);    //申请信号量2
    for(i = 0; i < 10; i++)
    {
        printf("thread2--%d\n", num[i]);
    }
    pthread_exit(NULL);
}

int main( int argc, const char *argv[])
{
    pthread_t thread1, thread2;
    if(pthread_create(&thread1, NULL, fun1, NULL) != 0)
    {
        perror("pthread_create thread1");
        return -1;
    }

    if(pthread_create(&thread2, NULL, fun2, NULL) != 0)
    {
        perror("pthread_create thread2");
        return -1;
    }
    if(sem_init(&sem1, 0, 1) != 0) {
        perror("sem1 init");
        return -1;
    }
    if(sem_init(&sem2, 0, 1) != 0) {
        perror("sem2 init");
        return -1;
    }
    //sleep(1);
    //pthread_join(thread1, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}
